import { NextRequest } from 'next/server';
import { eventEmitter } from '@/utils/sse/EventEmitter';
import { EventData } from '@/utils/sse/Events';

export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';

export async function GET(request: NextRequest) {
  // 获取频道名称
  const channel = request.nextUrl.searchParams.get('channel');
  
  // 验证必要参数
  if (!channel) {
    return new Response('Missing channel parameter', { status: 400 });
  }

  try {
    const stream = new TransformStream();
    const writer = stream.writable.getWriter();
    const encoder = new TextEncoder();

    // 创建消息监听器
    const listener = (data: EventData) => {
      try {
        writer.write(encoder.encode(`data: ${JSON.stringify(data)}\n\n`));
      } catch (error) {
        console.error('Error writing to SSE stream:', error);
        writer.close().catch(console.error);
      }
    };

    // 订阅指定频道
    const unsubscribe = eventEmitter.subscribe(channel, listener);

    // 当连接关闭时，清理监听器
    request.signal.addEventListener('abort', () => {
      unsubscribe();
      writer.close().catch(console.error);
    });

    // 返回 SSE 响应
    return new Response(stream.readable, {
      headers: {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
      },
    });
  } catch (error) {
    console.error('Error establishing SSE connection:', error);
    return new Response('Internal Server Error', { status: 500 });
  }
}